/**
 * @author  sunyang
 * @mail    E-mail:sunyang@163.com
 * @create  Nov 10, 2010 2:27:30 PM
 * @name    com.igit.grp.affix.servlet.UploadParameter.java
 * @version 1.0
 */
package com.sy.servlet;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;

/**
 * 获取上传文件的参数.
 */@SuppressWarnings("deprecation")
public class UploadParameter {

	private HttpServletRequest request;
	
	/** 上传路径. */
	private static String affixDir = "/GRPAffixDir";
	/** 上传文件的参数集合 */
	private Map<String, String> upFileParameter;
	private String[] fileParameter;
	
	public void parseParameters() throws ServletException, IOException {

//		System.out.println("--- 开始加载附件 ---");

		int fileSizeLimit = 2097152000;
	    MultipartParser parser = new MultipartParser(request, fileSizeLimit);
	    Part p;
	    FilePart fp;
//	    ParamPart pp;
	    upFileParameter=new HashMap<String, String>();
	    upFileParameter.put("fileId",request.getParameter("fileId"));
	    upFileParameter.put("projectId",request.getParameter("projectId"));
	    upFileParameter.put("classType",request.getParameter("classType"));
	    try {
	    	while ((p = parser.readNextPart()) != null) {
//	    		if (p.isParam()) { //是普通参数变量
//	                pp = (ParamPart) p;
//	                String name = pp.getName();
//	                String value = pp.getStringValue();
//	                if (value != null && !value.equals("")) {
//	                    value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
//	                    upFileParameter.put(name,value);
//	                    System.out.println(name+"==="+value);
//	                }
//	            }
	    		if (p.isFile()) { //是文件
                    fp = (FilePart) p;
                    String filename = fp.getFileName();
                    filename=new String(filename.getBytes("ISO-8859-1"), "UTF-8");
//                  System.out.println("filename=="+filename);
                    String name = null;
                    int pos = filename.lastIndexOf(File.separator);
                    if (pos != -1) {
                        name = filename.substring(pos);
                    } else {
                        name = filename;
                    }
                    // 附件名唯一性：时间戳+UUID
                    // weizh 2009-07-07
                    UUID uid = UUID.randomUUID();
                    String imageFileName = new Date().getTime() + uid.toString() + name;
                    
					File imageFile = new File(request.getRealPath(affixDir) + "/" + imageFileName);
                    File path = new File(request.getRealPath(affixDir));
                    if (!path.exists()) {
                        path.mkdir();
                    }
                    long canRead =fp.writeTo(imageFile);
                    fileParameter = new String[4];
                    fileParameter[0]=filename;//文件名
                    fileParameter[1] = this.getAffixSize(canRead);//文件大小
                    fileParameter[2] = fp.getContentType();//文件打开流格式
                    fileParameter[3] = affixDir + "/" + imageFileName;//修改后的文件名
	             }
	        }
	    } catch (Exception e) {
	    }
//		System.out.println("--- 加载完毕 ---");		
	}
	
    /**
     * 得到附件的大小
     * @param f
     * @return
     */
    private String getAffixSize(long size) {
        DecimalFormat df = new DecimalFormat("#.##");
        BigDecimal b1 = new BigDecimal(size);
        BigDecimal b2 = new BigDecimal(1024);
        MathContext m = new MathContext(3);
        String affixSize = df.format(b1.divide(b2, m)) + "KB";
        return affixSize;
    }
    /**
     * 获取文件后缀名
     * @param filename
     * @return
     */
	protected String getFilenameExtension(String filename) {
	    String defaultExt = ".bin";
	    if ((filename == null) || (filename.length() <= 0)) {
	        return defaultExt;
	    }
	    int i = filename.lastIndexOf('.');
	    if (i == -1) {
	        return defaultExt;
	    }
	    if ((i + 1) >= filename.length()) {
	        return defaultExt;
	    }
	    return filename.substring(i);
	}

	public UploadParameter(HttpServletRequest request) {
		this.request = request;
	}

	public Map<String, String> getUpFileParameter() {
		return upFileParameter;
	}

	public String[] getFileParameter() {
		return fileParameter;
	}

}